package com.my.controller;

import cn.hutool.core.lang.tree.TreeUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.my.entity.GradeClass;
import com.my.service.GradeClassService;
import com.my.util.Rest;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

@RestController
@CrossOrigin
public class GradeClassController {

    @Resource
    private GradeClassService service;

    @GetMapping("grade/get")
    public Rest get() {
        return Rest.ok().setData("tree", TreeUtil.build(service.getList(), 0L, (g, t) -> {
            t.setId(g.getId());
            t.setParentId(g.getParentId());
            t.setName(g.getName());
            t.putExtra("deep", g.getDeep());
            t.putExtra("sort", g.getSort());
            t.putExtra("gradeName", g.getGradeName());
            t.putExtra("createName", g.getCreateTime());
        }));
    }

    @GetMapping("grade/tree")
    public Rest tree() {
        List<GradeClass> list = new ArrayList<>();
        list.add(new GradeClass().setId(0L).setParentId(-1L).setName("目录").setDeep(-1));
        list.addAll(service.getList());
        return Rest.ok().setData("tree", TreeUtil.build(list, -1L, (g, t) -> {
            t.setId(g.getId());
            t.setParentId(g.getParentId());
            t.setName(g.getName());
            t.putExtra("title", g.getName());
            t.putExtra("deep", g.getDeep());
            t.putExtra("parentName", g.getGradeName() == null ? "" : g.getGradeName());
        }));
    }

    @PostMapping("grades")
    public Rest add(@RequestBody GradeClass gradeClass) {
        if(service.save(gradeClass)) {
            return Rest.ok("保存成功！");
        }
        return Rest.err("保存失败！");
    }

    @PutMapping("grades")
    public Rest edit(@RequestBody GradeClass gradeClass) {
        if(service.updateById(gradeClass)) {
            return Rest.ok("修改成功！");
        }
        return Rest.err("修改失败！");
    }

    @DeleteMapping("grades")
    public Rest delete(Long id) {
        if(!service.list(new QueryWrapper<GradeClass>().eq("parent_id", id)).isEmpty()) {
            return Rest.err("无法删除，此节点下还有子节点！");
        }
        if(service.removeById(id)) {
            return Rest.ok("删除成功！");
        }
        return Rest.err("删除失败！");
    }

}
